package com.yms.yms.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.yms.yms.common.BaseResponse;
import com.yms.yms.service.AuthService;
import com.yms.yms.utils.StatusCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {
    @Autowired
    private AuthService authService;

    private boolean root_generated = false;

    @PostMapping("/login")
    public BaseResponse login(
            @RequestParam("username") String username,
            @RequestParam("password") String password
    )
    {
        log.info("username:{}\tpassword:{}", username, password);
        return authService.login(username, password);
    }

    @PostMapping("/register")
    public BaseResponse register(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("email") String email,
            @RequestParam("realName") String realName
    )
    {
        log.info("Register--- name:{}, password:{}, email:{}. realName:{}", username, password, email, realName);
        return authService.register(username, password, email, realName);
    }

    @SaCheckLogin
    @PostMapping("/logout")
    public BaseResponse logout() {
        log.info("Logout");
        return authService.logout();
    }


    @SaCheckLogin
    @SaCheckRole("admin")
    @PostMapping("/role/assign")
    public BaseResponse assignRole() {
        // Todo 实现角色分配
        return null;
    }

    @SaCheckLogin
    @SaCheckRole("admin")
    @PostMapping("/role/revoke")
    public BaseResponse revokeRole(
            @RequestBody Map<String,Object> params
    )
    {
        // Todo 实现角色回收
        String username = (String) params.get("username");
        String rolename = (String) params.get("rolename");
        return null;
    }

    /**
     * 用于项目第一次启动创建第一个管理员用户
     * @return
     */
    @PostMapping("/root/generate")
    public BaseResponse generateRoot() {
        // Todo 将检测flag改为检测数据库
        if (!root_generated) {
            root_generated = true;
            return authService.generateRoot();
        }else{
            return new BaseResponse(StatusCodeEnum.FAILED, null);
        }
    }

    @SaCheckLogin
    @GetMapping("/testLogin")
    public BaseResponse testLogin() {
        log.debug("Test SaToken Login");
        return authService.testLogin();
    }
}
